import React, { useCallback, useEffect, useRef, useState } from "react";
import style from "./infoScroll.module.scss";

const InfoScroll = ({ infoList = [], maxLength = 3, speed = 1 }) => {
  const [mapList, setMapList] = useState(infoList);
  const infoScrollContainer = useRef(null);
  const innerScrollBox = useRef(null);
  const timer = useRef(null);

  const scrollFun = useCallback(() => {
    // 数组长度 <= 设置的最大长度，则不做滚动处理
    if (infoList.length <= maxLength) return;
    // 两倍数据，用于滚动渲染
    setMapList(infoList.concat(infoList));
    // 一条数据的默认高度
    const oneInfoHeight = 40;
    const infoListHeight = innerScrollBox.current.offsetHeight;
    // 默认屏幕刷新率
    const fps = 60;
    // 当前滚动的高度
    let currentScrollHeight = 0;
    // requestAnimationFrame实现滚动高度增加
    timer.current = requestAnimationFrame(function fn() {
      if (currentScrollHeight < infoListHeight) {
        currentScrollHeight += oneInfoHeight / fps / speed;
        innerScrollBox.current.style.transform =
          "translateY(-" +
          Math.min(currentScrollHeight, infoListHeight) +
          "px)";
      } else {
        currentScrollHeight = 0;
        innerScrollBox.current.style.transform = "translateY(0px)";
      }
      timer.current = requestAnimationFrame(fn);
    });
  }, [infoList, maxLength, speed]);

  const handelInfoScrollContainerHeight = useCallback(
    () => (infoScrollContainer.current.style.height = 40 * maxLength + "px"),
    [maxLength]
  );

  useEffect(() => {
    handelInfoScrollContainerHeight();
    scrollFun();
    return () => cancelAnimationFrame(timer.current);
  }, [handelInfoScrollContainerHeight, scrollFun]);

  return (
    <div className={style.infoScrollContainer} ref={infoScrollContainer}>
      <div className={style.innerScrollBox} ref={innerScrollBox}>
        {mapList.map((item, index) => {
          return (
            <div className={style.text} key={index}>
              {item}
            </div>
          );
        })}
      </div>
    </div>
  );
};

export default InfoScroll;
